package com.mf.morefun.ui.userinfo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.MessageBean;
import com.mf.morefun.bean.RegisterBean;
import com.mf.morefun.requestbean.RequestMessageBean;
import com.mf.morefun.requestbean.RequestRegisterBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.FileUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

public class RegisterActivity extends BaseBusActivity {
    @BindView(R.id.edit_user)
    EditText editUser;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.v_username)
    View vUsername;
    @BindView(R.id.edit_verification)
    EditText editVerification;
    @BindView(R.id.tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.v_verification)
    View vVerification;
    @BindView(R.id.edit_invitation)
    EditText editInvitation;
    @BindView(R.id.v_invitation)
    View vInvitation;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    private RoundProcessDialog dialog;
    private SPUtils mSputils;

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        dialog = new RoundProcessDialog(RegisterActivity.this, "");
        mSputils = new SPUtils(getApplicationContext());
        editUser.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    vUsername.setBackgroundResource(R.color.main_default_color);
                    vVerification.setBackgroundColor(0xffC5C5C5);
                    vInvitation.setBackgroundColor(0xffC5C5C5);
                }
            }
        });
        editVerification.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    vUsername.setBackgroundColor(0xffC5C5C5);
                    vVerification.setBackgroundResource(R.color.main_default_color);
                    vInvitation.setBackgroundColor(0xffC5C5C5);
                }
            }
        });
        editInvitation.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    vUsername.setBackgroundColor(0xffC5C5C5);
                    vVerification.setBackgroundColor(0xffC5C5C5);
                    vInvitation.setBackgroundResource(R.color.main_default_color);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }
    private String vCode = "";
    @OnClick({R.id.iv_clear, R.id.tv_getcode, R.id.tv_info, R.id.tv_start, R.id.tv_login})
    public void onViewClicked(View view) {
        Intent mIntent = null;
        switch (view.getId()) {
            case R.id.iv_clear:
                editUser.setText("");
                break;
            case R.id.tv_getcode:
                if (StringUtils.isEmpty(editUser.getText().toString())) {
                    ToastUtils.show(getApplicationContext(), "手机不能为空", 100);
                    return;
                }
                if (editUser.getText().toString().length() != 11 || !editUser.getText().toString().substring(0, 1).equals("1")) {
                    ToastUtils.show(getApplicationContext(), "请输入正确的手机号码", 100);
                    return;
                }
                count = 60;
                initGetMessageHttp(editUser.getText().toString());
                tvGetcode.setEnabled(false);
                break;
            case R.id.tv_info:
                break;
            case R.id.tv_start:
                if (StringUtils.isEmpty(editUser.getText().toString())) {
                    ToastUtils.show(getApplicationContext(), "手机不能为空", 100);
                    return;
                }
                if (editUser.getText().toString().length() != 11 || !editUser.getText().toString().substring(0, 1).equals("1")) {
                    ToastUtils.show(getApplicationContext(), "请输入正确的手机号码", 100);
                    return;
                }
                if (StringUtils.isEmpty(editVerification.getText().toString())){
                    ToastUtils.show(getApplicationContext(), "请输入验证码", 100);
                    return;
                }
                if (!editVerification.getText().toString().equals(vCode)){
                    ToastUtils.show(getApplicationContext(), "请输入正确的验证码", 100);
                    return;
                }
                if (StringUtils.isEmpty(editInvitation.getText().toString())){
                    ToastUtils.show(getApplicationContext(), "请输入邀请码", 100);
                    return;
                }
                initRegisterHttp(editUser.getText().toString(), editInvitation.getText().toString());
                break;
            case R.id.tv_login:
                mIntent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(mIntent);
                finish();
                break;
        }
    }

    //获取短信验证吗
    private void initGetMessageHttp(String user){
        if (null != dialog){
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.GETMESSAGECODE);
        RequestMessageBean bean = new RequestMessageBean();
        bean.setMobile(user);
        params.setBodyContent(JSON.toJSONString(bean));
        params.setCharset("UTF-8");
        params.addHeader("Content-Type", "application/json");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != dialog){
                    dialog.cancel();
                }
                if (!StringUtils.isEmpty(result)){
                    MessageBean messageBean = JSON.parseObject(result, MessageBean.class);
                    if (messageBean.getErrorCode() == 0){
                        editUser.setFocusable(false);
                        ivClear.setVisibility(View.INVISIBLE);
                        vCode = messageBean.getResult().getVarifyCode();
                        showCounter();
                    }else {
                        ToastUtils.show(getApplicationContext(), messageBean.getMessage(), 100);
                        tvGetcode.setEnabled(true);
                    }
                }else {
                    ToastUtils.show(getApplicationContext(), "短信发送失败", 100);
                    tvGetcode.setEnabled(true);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog){
                    dialog.cancel();
                }
                tvGetcode.setEnabled(true);
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private int count = 60;
    private Thread mThread;
    private boolean isRunnig = true;
    private void showCounter() {
        if (null != mThread) {
            mThread.interrupt();
            mThread = null;
        }
        isRunnig = true;
        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunnig) {
                    try {
                        Thread.sleep(1000);
                        if (count > 0) {
                            count--;
                            Message message = new Message();
                            message.what = 0;
                            message.arg1 = count;
                            mHandler.sendMessage(message);
                        } else {
                            mHandler.sendEmptyMessage(1);
                            isRunnig = false;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (UnsupportedOperationException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        mThread.start();
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    tvGetcode.setText(String.valueOf(msg.arg1) + "S");
                    break;
                case 1:
                    tvGetcode.setText("获取验证码");
                    tvGetcode.setEnabled(true);
                    if (null != mThread) {
                        mThread.interrupt();
                        mThread = null;
                    }
                    break;
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(RegisterActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mThread) {
            mThread.interrupt();
            mThread = null;
        }
    }

    //注册
    private void initRegisterHttp(String user, String invitationedCode){
        if (null != dialog){
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.REGISTER);
        RequestRegisterBean bean = new RequestRegisterBean();
        bean.setPhone(user);
        bean.setPassword(FileUtils.md5((user.substring(5))));
        bean.setUserType("1");
        if (StringUtils.isEmpty(invitationedCode)){
            bean.setInvitationedCode("");
        }else {
            bean.setInvitationedCode(invitationedCode);
        }
        bean.setEnableEnd(DateUtils.DEFAULT_DATE_FORMAT.format(new Date((System.currentTimeMillis() + 604800000))));
        params.setBodyContent(JSON.toJSONString(bean));
        params.setCharset("UTF-8");
        params.addHeader("Content-Type", "application/json");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != dialog){
                    dialog.cancel();
                }
                if (!StringUtils.isEmpty(result)){
                    RegisterBean registerBean = JSON.parseObject(result, RegisterBean.class);
                    if (registerBean.getErrorCode() == 0){
                        mSputils.putString(Configuration.USERPHONE, user);
                        Intent mIntent = new Intent(RegisterActivity.this, LoginActivity.class);
                        startActivity(mIntent);
                        finish();
                    }else {
                        ToastUtils.show(getApplicationContext(), registerBean.getMessage(), 100);
                    }
                }else {
                    ToastUtils.show(getApplicationContext(), "注册失败", 100);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog){
                    dialog.cancel();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
